<!--
 * @Description: 计划详情
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2023-03-15 10:26:38
 * @LastEditTime: 2023-05-22 09:37:16
 * @FilePath: \cscec-pms-admin\src\views\construction\weekPlan\components\PlanDetail.vue
-->
<template>
  <div class="week-plan-plan-detail">
    <title-name>
        <div class="title-wrapper">
          <span v-if="businessType === '0'">上周逾期未完成节点</span>
          <span v-else-if="businessType === '1'">本周计划</span>
          <span v-else-if="businessType === '2'">下周重点计划</span>
          <template>
            <span class="tips">父级阶段类别的完成状态请在“树状视图”下设置</span>
          <a-button
                type="primary"
                icon="unordered-list"
                :ghost="!viewMode"
                :disabled="loading"
                @click="changeViewMode(true)"
              >
                平铺视图
              </a-button>
              <a-button
                type="primary"
                :ghost="viewMode"
                :disabled="loading"
                @click="changeViewMode(false)"
              >
                <BaseSvgIcon
                  class="icon-item"
                  icon="tree"
                />
                树状视图
              </a-button>
        </template>    
        </div>
      </title-name>
    <div
      v-if="!viewMode"
      class="btn-wrapper"
    >
      <a-button
        type="primary"
        :disabled="loading"
        @click="$refs.table.setAllTreeExpansion()"
      >
        展开全部
      </a-button>
      <a-button
        type="primary"
        :disabled="loading"
        @click="$refs.table.clearTreeExpand()"
      >
        收起全部
      </a-button>
    </div>
    <div class="pub-table-select-count">
      <a-icon
        type="info-circle"
        theme="twoTone"
      />
      <span>
        项目：<span class="totalNum">{{ tableInfo.projectName }}</span>
      </span>
      <span>
        节点共 <span class="totalNum">{{ tableInfo.nodeTotalNum }}</span> 项
      </span>
      <span>
        一级节点共 <span class="totalNum">{{ tableInfo.firstNodeNum }}</span> 项
      </span>
      <span>
        二级节点共 <span class="totalNum">{{ tableInfo.secondNodeNum }}</span> 项
      </span>
      <span>
        三级节点共 <span class="totalNum">{{ tableInfo.threeNodeNum }}</span> 项
      </span>
      <span>
        周期天数 <span class="totalNum">{{ tableInfo.periodDay }}</span> 天
      </span>
      <span>
        周期间隔 <span class="totalNum">{{ tableInfo.periodDate }}</span>
      </span>
    </div>
    <!-- 搜索 -->
    <a-form-model
      :model="searchForm"
      layout="inline"
      class="plan-detail-search"
    >
      <a-form-model-item>
        <b>搜索:</b>
      </a-form-model-item>
      <a-form-model-item>
        <a-input
          v-model="searchForm.businessMatters"
          placeholder="节点名称"
          class="plan-detail-search-width"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-select
          v-model="searchForm.nodeControl"
          placeholder="节点管控级别"
          class="plan-detail-search-width"
          allowClear
        >
          <a-select-option
            v-for="item in nodeControlLevelList"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item>
        <a-range-picker
          v-model="searchForm.planStart"
          class="plan-detail-search-date"
          :placeholder="['计划开始时间起','计划开始时间止']"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-range-picker
          v-model="searchForm.planEnd"
          class="plan-detail-search-date"
          :placeholder="['计划完成时间起','计划完成时间止']"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-range-picker
          v-model="searchForm.completeDate"
          class="plan-detail-search-date"
          :placeholder="['实际完成时间起','实际完成时间止']"
        />
      </a-form-model-item>
      <a-form-model-item>
          <a-select
            v-model="searchForm.reviewStatus"
            placeholder="复核状态"
            class="plan-detail-search-width"
            allowClear
          >
            <a-select-option
              v-for="item in reviewStatusList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-input
            v-model="searchForm.reviewEmployeeName"
            placeholder="复核人名称"
            class="plan-detail-search-width"
          />
        </a-form-model-item>
      <a-form-model-item>
        <a-select
          v-model="searchForm.workStatus"
          placeholder="节点状态"
          class="plan-detail-search-width"
          allowClear
        >
          <a-select-option
            v-for="item in nodeStatusList"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item>
        <a-button
          type="primary"
          :loading="loading"
          @click="loadData(true)"
        >
          搜索
        </a-button>
        <a-button
          :disabled="loading"
          class="ml12"
          @click="handleReset"
        >
          重置
        </a-button>
      </a-form-model-item>
    </a-form-model>
    <!-- 搜索 -->
    <a-spin :spinning="loading">
      <u-table
        ref="table"
        fixed-columns-roll
        :height="500"
        show-header-overflow
        :tree-config="viewMode ? {} : {
          children: 'childTree',
          expandAll: false,
        }"
        row-id="id"
        :use-virtual="true"
        border
      >
        <!-- :fixed="item.dataIndex === 'sortNum' || item.dataIndex === 'phaseCategory'" -->
        <u-table-column
          v-for="item in columns2"
          :key="item.dataIndex"
          :prop="item.dataIndex"
          :label="item.title"
          :width="item.width"
          :tree-node="item.dataIndex === 'phaseCategory'"
          align="center"
        >
          <template v-slot="{ row }">
            <span
              :title="row[item.dataIndex]"
              class="span-ellipsis"
            >
              <template v-if="row.nodeType === 0">
                <template v-if="['sortNum','phaseCategory','businessMatters','period','planStartTime','planEndTime'].includes(item.dataIndex)">
                  {{ row[item.dataIndex] }}
                </template>
                <!-- 复核情况 -->
                <template v-else-if="item.dataIndex === 'nodeStatusName'">
                  <span>{{  getNodeStatusName(row) }} </span>
                </template>
                <template v-else-if="item.dataIndex === 'reviewStatus'">
                  <a
                    v-if="row.reviewStatus && row.reviewStatus !== '-'"
                    @click="handleNodeReviewRecord(row)"
                  >{{ row.reviewStatus }}</a>
                  <span v-else>-</span>
                </template>
              </template>
              <template v-else>
                <span
                  v-if="item.dataIndex === 'sortNum'"
                  :class="indexClass(row)"
                  class="sort-num"
                >
                  <span>{{ row[item.dataIndex] }}</span>
                </span>
                <template v-else-if="item.dataIndex === 'controlLevelId'">
                  {{ row.controlLevelName }}
                </template>
                <!-- 复核情况 -->
                <template v-else-if="item.dataIndex === 'reviewStatus'">
                  <a
                    v-if="row.reviewStatus && row.reviewStatus !== '-'"
                    @click="handleNodeReviewRecord(row)"
                  >{{ row.reviewStatus }}</a>
                  <span v-else>-</span>
                </template>
                <template v-else-if="item.dataIndex === 'directResPerList'">
                  {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                </template>
                <template v-else>
                  {{ row[item.dataIndex] }}
                </template>
              </template>
            </span>
          </template>
        </u-table-column>
        <u-table-column
          key="operation"
          prop="operation"
          label="操作"
          width="200"
          align="center"
          :fixed="'right'"
        >
          <template v-slot="{ row }">
            <MoreButton
              v-if="row.nodeType === 1"
              :key="row.id + new Date().getTime()"
            >
              <a @click="handleNodeCompletion(row,'detail')">查看</a>
              <a
                v-if="(row.nodeStatus === 0 || row.nodeStatus === 1 || row.nodeStatus === 3 || row.nodeStatus === 7) && JSON.parse($route.query.thisWeek || false)"
                v-btnPermission="'pm_066_fin_04'"
                @click="handleNodeCompletion(row,'update')"
              >节点完成</a>
              <a
              v-if="row.nodeType === 1 && row.status*1!==0"
                @click="$bus.$emit('showApprovalDetailsDialog', row.id)"
              >审批信息</a>
               <a  v-if="row.nodeType === 1 && (row.nodeStatus === 4 || row.nodeStatus === 5)"
                  v-btnPermission="'pm_066_fuh_08'"
                  @click="handleNodeReview(row)"
                >复核</a>
            </MoreButton>
            <a  v-if="row.changeComplete && row.nodeType*1===0"
              v-btnPermission="'pm_066_ffi_07'"
              @click="handlerStageClassComple(row)"
              >设置完成情况</a>
          </template>
        </u-table-column>
      </u-table>
    </a-spin>
    <!-- 节点完成 -->
    <NodeCompletion
      :visible.sync="nodeCompletionVisible"
      :source="nodeCompletionSource"
      @refresh="loadData"
    />
    <!-- 节点完成 -->
    <!-- 阶段/类别完成情况 -->
    <StageClassComple :visible.sync="stageClassCompleVisible" :isSetupComplete="isSetupComplete" @submit="setSubmit" :rowName="rowName"></StageClassComple>
    <!-- 阶段/类别完成情况 -->
    <!-- 复核 -->
    <NodeReview :visible.sync="nodeReviewVisible" type="1" :nodeId="nodeReviewId" @submit="handleNodeReviewSubmit"></NodeReview>
    <!--复核 -->
    <!-- 复核记录-->
    <NodeReviewRecord :visible.sync="nodeReviewRecordVisble" :nodeId="nodeReviewId"></NodeReviewRecord>
    <!--复核记录 -->
  </div>
</template>
<script>
import { nodeControlLevelList, nodeStatusList, columns2,reviewStatusList} from '../model.js'
import { UTable, UTableColumn } from 'umy-ui'
import NodeCompletion from './NodeCompletion'
import StageClassComple from './stageClassComple'
import NodeReview from '@/views/construction/components/NodeReview'
import NodeReviewRecord from '@/views/construction/components/NodeReviewRecord'
import weekPlanApi from '@/api/construction/weekPlanApi'
export default {
  name: 'PlanDetail' + Date.now(),
  components: {
    UTable,
    UTableColumn,
    NodeCompletion,
    StageClassComple,
    NodeReview,
    NodeReviewRecord
  },
  props: {
    // 视图模式,true:平铺视图,false:树状视图
    // 加载中
    load:{
      type: Boolean,
      default: false
    },
    businessType:{
      type: String,
      default: ''
    },
    allData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      // 加载
      loading: this.load,
      // 表格信息
      tableInfo: {
        projectName: void 0,
        nodeTotalNum: void 0,
        firstNodeNum: void 0,
        secondNodeNum: void 0,
        threeNodeNum: void 0,
        periodDay: void 0,
        periodDate: void 0
      },
      // 搜索表单
      searchForm: {},
      // 是否搜索
      isSearch: false,
      // 节点管控级别列表
      nodeControlLevelList,
      // 节点状态列表
      nodeStatusList,
      // 复核状态列表
      reviewStatusList,
      // 表格数据
      tableData: [],
      // 表头
      columns2,
      // 节点完成隐藏显示
      nodeCompletionVisible: false,
      //阶段/类别完成情况
      stageClassCompleVisible:false,
      //是否设置完成情况
      isSetupComplete:false,
      //节点复核
      nodeReviewVisible:false,
      // 节点 id
      nodeReviewId: '',
      //复核记录
      nodeReviewRecordVisble:false,
      // 节点完成数据
      nodeCompletionSource: {},
      // 审批信息隐藏显示
      visibleApprove: false,
      // 业务id
      businessId: void 0,
      viewMode:true,
      rowId:null,   //当前行id
      rowName:null,  //当前行阶段类别
    }
  },
  watch: {
    // 监听加载父组件按钮禁用
    loading:{
      handler(val){
        this.$emit('update:load',val)
      }
    },
    allData: {
      handler(val) {
        this.loading = true;
        if (val) {
          this.loading = false;
          if (val.listVO) {
            this.tableData = val.listVO
          }
          this.tableInfo = {
            projectName:val.projectName,
            nodeTotalNum: val.nodeTotalNum || 0, // 一级节点
            firstNodeNum: val.firstNodeNum || 0, // 二级节点
            secondNodeNum: val.secondNodeNum || 0, // 三级节点
            threeNodeNum: val.threeNodeNum || 0, // 周天总数
            periodDay: val.periodDay || 0, // 周期天数
            periodDate: (val.planStartTime ?? '' !== '') && (val.planEndTime ?? '' !== '') ? val.planStartTime + '--' + val.planEndTime : '--' || 0, // 周期间隔
          }
        }
        
      }
    },
    // 表格数据监听
    tableData: {
      handler(list) {
        if (this.$refs.table) {
          // 获取之前展开数据
          const expandRecords = this.$refs.table.getTreeExpandRecords()
          // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
          const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
          const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
          // 加载数据
          this.$refs.table.reloadData(list).then(() => {
            // 是搜索默认展开全部
            if (this.isSearch) {
              this.$refs.table.setAllTreeExpansion()
              this.isSearch = false
            } else {
              // 数据加载完成出现之后，打开之前的展开行
              expandRecords.forEach((row) => {
                this.$refs.table.setTreeExpansion(row, true)
              })
            }
            // 还原之前滚动高度
            this.$refs.table.pagingScrollTopLeft(scrollTop + 1, scrollLeft)
            this.$nextTick(()=>{
              // 不加这一步，列表操作栏 会变形
              this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
            })
          })
        }
      }
    }
  },
  methods: {
    //设置节点状态字段
    getNodeStatusName(row){
       let text = '';
      if(row.nodeStatus*1===0 && row.inherit){
        text = '未全部完成';
      }else if(row.nodeStatus*1===1  && row.inherit){
        text = '全部完成';
      }else{
        text = row.nodeStatusName;
      }
      return text;

    },
    changeViewMode(mode) {
        // 视图模式,true:平铺视图,false:树状视图
        this.viewMode = mode
        this.loadData()
      },
    /**
     * @description: 获取搜索参数
     * @return {Object}
     */
     getSearchParms() {
      let planStartOrigin = void 0,
        planStartOver = void 0,
        planEndOrigin = void 0,
        planEndOver = void 0
      if (Array.isArray(this.searchForm?.planStart) && this.searchForm.planStart.length > 0) {
        planStartOrigin = this.searchForm.planStart[0].format('YYYY-MM-DD')
        planStartOver = this.searchForm.planStart[1].format('YYYY-MM-DD')
      }
      if (Array.isArray(this.searchForm?.planEnd) && this.searchForm.planEnd.length > 0) {
        planEndOrigin = this.searchForm.planEnd[0].format('YYYY-MM-DD')
        planEndOver = this.searchForm.planEnd[1].format('YYYY-MM-DD')
      }
      const { businessMatters, nodeControl,workStatus,reviewStatus,reviewEmployeeName} = this.searchForm
      return {
        businessMatters,
        nodeControl,
        planStartOrigin,
        planStartOver,
        planEndOrigin,
        planEndOver,
        workStatus,
        planId: this.$route.query.planId + '',
        businessType: this.businessType,
        reviewStatus, 
        reviewEmployeeName 
      }
    },
    /**
     * @description: 表格数据加载方法
     * @param {boolean} isSearch 是否搜索
     * @return {Promise} 接口Promise
     */
     async loadData(isloading = true, isSearch = false) {
      try {
        if (isloading) {
          this.loading = true
        }
        if (isSearch) {
          this.isSearch = isSearch
        }
        // true:平铺,false:树
        const apiMode = this.viewMode
        const fun = apiMode ? weekPlanApi.weekPlanTileSearch :  weekPlanApi.weekPlanDetailSearch
        const {
          code,
          data,
        } = await fun(this.isAudit ? {businessType: this.businessType,planId: this.projectId } : this.getSearchParms())
        if (code === this.SUCCESS_CODE) {
          const { projectName, nodeTotalNum, firstNodeNum, secondNodeNum, threeNodeNum, periodDay, planStartTime, planEndTime, treeListVO, listVO } = data[0];
          this.tableInfo = {
            projectName,
            nodeTotalNum,
            firstNodeNum,
            secondNodeNum,
            threeNodeNum,
            periodDay,
            periodDate: (planStartTime ?? '' !== '') && (planEndTime ?? '' !== '') ? planStartTime + '--' + planEndTime : '--'
          }
          // if(!treeListVO[0].phaseCategory){
          //   treeListVO[0].phaseCategory = '222';
          // }
          this.tableData = apiMode ? listVO : treeListVO[0]?.childTree;
        }
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      } finally {
        if (isloading) {
          this.loading = false
        }
      }
    },
    /**
     * @description: 重置搜索
     * @return {void}
     */
    handleReset() {
      this.searchForm = {}
      this.loadData()
    },
    /**
     * @description: 节点完成
     * @param {object} row 行数据
     * @param {string} type 查看/节点完成
     * @return {void}
     */
    handleNodeCompletion(row, type) {
      this.nodeCompletionVisible = true
      this.nodeCompletionSource = {
        type,
        data: row,
        rowName:row.parentName || row.phaseCategory
      }
    },
    /**
     * @description: 索引类名
     * @param {object} row 行数据
     * @return {string}
     */
    indexClass(row) {
      return row.promptLights === 1 || row.promptLights === 2 ? '' : 'class-' + row.statusLights
    },
    //阶段完成
    handlerStageClassComple(row){
       this.stageClassCompleVisible= true;
       this.isSetupComplete = true;
       this.rowId = row?.id;
       this.rowName = row.phaseCategory || row.parentName;
    },
    //设置完成情况提交
    setSubmit(data,flag){
      if(!flag){
        return
      }
       let obj ={
        completeStatus:data.completeStatus,
        id:this.rowId
       }
       this.loading = true;
       weekPlanApi.editWorkPack(obj).then((res)=>{
          if(res.code==200){
            this.$message.success('设置成功！');
            this.loading = false;
            this.loadData()
          }
       })
    },
    //节点复核
    handleNodeReview(row){
      this.nodeReviewId = row.id
      this.nodeReviewVisible = true;
    },
    handleNodeReviewSubmit() {
      this.loadData()
    },
    // 复核记录
    handleNodeReviewRecord(row){
      this.nodeReviewId = row.id
      this.nodeReviewRecordVisble = true;
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.title-wrapper {
  display: flex;    
  .tips {
    color: red;
    font-size: 14px;
    margin-left: auto;
    line-height: 32px;
    font-weight: 300;
    margin-right: 6px;
  }
  > button {
    margin-left: 6px;
    &:first-of-type {
      margin-left: 0;
    }
  }
}
.plan-board-detail {
  margin-top: 15px;
}
.btn-wrapper {
  margin: 0 -5px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  > button,
  > span,
  > div {
    margin: 5px;
  }
}
.pub-table-select-count {
  > span {
    margin-right: 12px;
  }
}
.sort-num {
  display: block;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    margin-right: 5px;
    width: 16px;
    height: 16px;
  }
}
.class-0,
.class-1,
.class-2,
.class-3,
.class-4 {
  color: #fff;
}
.class-0 {
  // background-color: #d1d1d1;
  color: #606266;
}
.class-1 {
  color: #606266;
}
.class-2 {
  background-color: #f85c62;
}
.class-3 {
  background-color: #1dc682;
}
.class-4 {
  background-color: #ffced0;
}

.plan-detail-search {
  margin-bottom: 10px;
  @{deep} .ant-form-item .ant-form-item-label {
    width: 0;
  }
  @{deep} .ant-form-item .ant-form-item-control-wrapper {
    width: 100%;
  }
}
.plan-detail-search-width {
  width: 150px;
}
.plan-detail-search-date {
  width: 260px;
}
.activity-on-arrow {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-left: 5px;
}
.operation-btn{
  text-align: right;
  button{
    &:last-child{
      margin-left: 10px;
    }
  }
}
.plan-board-detail-search-width {
  width: 200px;
}

</style>
